package info.motteke.mybws.xml;

import info.motteke.mybws.MyBws;
import info.motteke.mybws.MyBwsBuilder;
import info.motteke.mybws.Node;
import info.motteke.mybws.exception.XmlParseException;
import info.motteke.mybws.impl.MyBwsImpl;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class XmlParser implements MyBwsBuilder {

    public Node parse(InputStream in) throws IOException {
        Throwable cause;

        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();

            NodeHandler handler = new NodeHandler();
            parser.parse(in, handler);

            return handler.getRoot();
        } catch (SAXException e) {
            cause = e;
        } catch (ParserConfigurationException e) {
            cause = e;
        }

        throw new XmlParseException(cause);
    }

    @Override
    public MyBws build(InputStream in) throws IOException {
        return new MyBwsImpl(parse(in));
    }
}
